/**
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

package org.elephantt.webby;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * A 200 OK response where the body is a FreeMarker template. Use the setGlobalConfiguration() method to configure globally; otherwise
 * use the constructor that accepts a Configuration for the instance.
 *
 * @link http://freemarker.sourceforge.net/
 */
public class FtlViewResponder implements Responder {
  private final Configuration configuration;
  private final String defaultContentType;

  public FtlViewResponder(Configuration configuration, String defaultContentType) {
    this.configuration = configuration;
    this.defaultContentType = defaultContentType;
  }

  public String render(String filename, Object root) throws IOException, TemplateException {
    Template template = configuration.getTemplate(filename);
    assert template != null;
    StringWriter writer = new StringWriter();
    template.process(root, writer);
    return writer.toString();
  }

  public void respond(HttpServletRequest request, HttpServletResponse response, Object controllerReturnValue) throws IOException {
    FtlView ftlView;

    if (controllerReturnValue instanceof FtlView) {
      ftlView = (FtlView) controllerReturnValue;
    } else {
      RequestMapping mapping = (RequestMapping) request.getAttribute(ServletRequestAttributes.REQUEST_MAPPING);
      assert mapping != null : "request missing required attribute " + ServletRequestAttributes.REQUEST_MAPPING;
      ftlView = new FtlView(mapping.getViewNamePrefix() + ".ftl", controllerReturnValue);
    }

    String contentType = ftlView.getContentType();
    if (contentType == null) {
      contentType = defaultContentType;
    }

    if (contentType != null) {
      response.setContentType(ftlView.getContentType());
    }


    Template template = configuration.getTemplate(ftlView.getFilename());
    assert template != null; // freemarker will throw an RTE if it can't find the template

    try {
      // buffer the output so we don't write bytes in the case the template processing has an error
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      template.process(ftlView.getModel(), new OutputStreamWriter(buffer));
      response.getOutputStream().write(buffer.toByteArray());
    } catch (TemplateException e) {
      throw new RuntimeException("Error merging FreeMarker template for template " + ftlView.getFilename() + " and root " + ftlView.getModel());
    }
  }
}